<template>
  <div class="project_expenses gl_fs_14">
    <div v-loading="projectLoading">
      <div class="gl_mb_15">
        <div v-if="projectObj.aType.length > 0">
          <div class="gl_mb_5">A类型项目：</div>
          <el-table class="expenses_table" :data="projectObj.aType" :show-header="false" size="mini">
            <el-table-column :min-width="300">
              <template slot-scope="{ row }">
                <span class="form_name">{{ row.categoryName }}：</span>
                <el-input v-model="row.charge.entryAmount" type="text" size="mini" class="gl_mr_5" style="width: calc(100% - 210px);" />
                <span>元</span>
              </template>
            </el-table-column>
            <el-table-column align="center" :min-width="200">
              <template slot-scope="{ row }">
                <span>A类兼项费：</span>
                <el-input v-model="row.charge.simultaneousEntryAmountA" type="text" size="mini" class="gl_mr_5" style="width: calc(100% - 100px);" />
                <span>元</span>
              </template>
            </el-table-column>
            <el-table-column align="center" :min-width="200">
              <template slot-scope="{ row }">
                <span>B类兼项费：</span>
                <el-input v-model="row.charge.simultaneousEntryAmountB" type="text" size="mini" class="gl_mr_5" style="width: calc(100% - 100px);" />
                <span>元</span>
              </template>
            </el-table-column>
            <el-table-column align="center" :min-width="200">
              <template slot-scope="{ row }">
                <span>C类兼项费：</span>
                <el-input v-model="row.charge.simultaneousEntryAmountC" type="text" size="mini" class="gl_mr_5" style="width: calc(100% - 100px);" />
                <span>元</span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('table.actions')" align="right" :width="100">
              <template slot-scope="{ row }">
                <el-button size="mini" type="text" @click="submitProjectExpenses(row)">确定</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-else>A类型项目：暂无</div>
      </div>
      <div class="gl_mb_15">
        <div v-if="projectObj.bType.length > 0">
          <div class="gl_mb_5">B类型项目：</div>
          <el-table class="expenses_table" :data="projectObj.bType" :show-header="false" size="mini">
            <el-table-column :min-width="300">
              <template slot-scope="{ row }">
                <span class="form_name">{{ row.categoryName }}：</span>
                <el-input v-model="row.charge.entryAmount" type="text" size="mini" class="gl_mr_5" style="width: calc(100% - 210px);" />
                <span>元</span>
              </template>
            </el-table-column>
            <el-table-column align="center" :min-width="200">
              <template slot-scope="{ row }">
                <span>A类兼项费：</span>
                <el-input v-model="row.charge.simultaneousEntryAmountA" type="text" size="mini" class="gl_mr_5" style="width: calc(100% - 100px);" />
                <span>元</span>
              </template>
            </el-table-column>
            <el-table-column align="center" :min-width="200">
              <template slot-scope="{ row }">
                <span>B类兼项费：</span>
                <el-input v-model="row.charge.simultaneousEntryAmountB" type="text" size="mini" class="gl_mr_5" style="width: calc(100% - 100px);" />
                <span>元</span>
              </template>
            </el-table-column>
            <el-table-column align="center" :min-width="200">
              <template slot-scope="{ row }">
                <span>C类兼项费：</span>
                <el-input v-model="row.charge.simultaneousEntryAmountC" type="text" size="mini" class="gl_mr_5" style="width: calc(100% - 100px);" />
                <span>元</span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('table.actions')" align="right" :width="100">
              <template slot-scope="{ row }">
                <el-button size="mini" type="text" @click="submitProjectExpenses(row)">确定</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-else>B类型项目：暂无</div>
      </div>
      <div class="gl_mb_15">
        <div v-if="projectObj.cType.length > 0">
          <div class="gl_mb_5">C类型项目：</div>
          <el-table class="expenses_table" :data="projectObj.cType" :show-header="false" size="mini">
            <el-table-column :min-width="300">
              <template slot-scope="{ row }">
                <span class="form_name">{{ row.categoryName }}：</span>
                <el-input v-model="row.charge.entryAmount" type="text" size="mini" class="gl_mr_5" style="width: calc(100% - 210px);" />
                <span>元</span>
              </template>
            </el-table-column>
            <el-table-column align="center" :min-width="200">
              <template slot-scope="{ row }">
                <span>A类兼项费：</span>
                <el-input v-model="row.charge.simultaneousEntryAmountA" type="text" size="mini" class="gl_mr_5" style="width: calc(100% - 100px);" />
                <span>元</span>
              </template>
            </el-table-column>
            <el-table-column align="center" :min-width="200">
              <template slot-scope="{ row }">
                <span>B类兼项费：</span>
                <el-input v-model="row.charge.simultaneousEntryAmountB" type="text" size="mini" class="gl_mr_5" style="width: calc(100% - 100px);" />
                <span>元</span>
              </template>
            </el-table-column>
            <el-table-column align="center" :min-width="200">
              <template slot-scope="{ row }">
                <span>C类兼项费：</span>
                <el-input v-model="row.charge.simultaneousEntryAmountC" type="text" size="mini" class="gl_mr_5" style="width: calc(100% - 100px);" />
                <span>元</span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('table.actions')" align="right" :width="100">
              <template slot-scope="{ row }">
                <el-button size="mini" type="text" @click="submitProjectExpenses(row)">确定</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-else>C类型项目：暂无</div>
      </div>
      <div class="gl_pb_15 gl_mb_15" style="width: 100%; border-bottom: 1px dotted #606266">
        <span>大团体项目：</span>
        <template v-if="projectObj.team.length > 0">
          <div v-for="item in projectObj.team" :key="item.categoryId" class="gl_dis_ib gl_mr_10">{{ item.categoryName }}</div>
        </template>
        <div v-else class="gl_dis_ib gl_mr_10">暂无</div>
      </div>
    </div>
    <el-row :gutter="20" class="gl_mb_20">
      <el-col :span="12">
        <el-table class="expenses_table" :data="showTableData" :loading="showTableLoading" :show-header="false" size="mini" style="width: 100%;">
          <el-table-column :min-width="200">
            <template slot-scope="{ row }">
              <span class="bottom_form_name">{{ row.name }}：</span>
              <el-input v-model="row.amount" type="text" size="mini" class="gl_mr_5" style="width: calc(100% - 100px);" />
              <span>元</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.actions')" align="right" :width="90">
            <template slot-scope="{ row }">
              <el-button size="mini" type="text" @click="submitExpenses(row)">确定</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="12">
        <el-table v-loading="tableLoading" :data="tableData" stripe size="mini" style="width: 100%;">
          <el-table-column prop="name" label="费用名称" :min-width="150" />
          <el-table-column label="金额（元）" align="center" :width="150">
            <template slot-scope="{ row }">
              <div style="line-height: 28px;">{{ row.amount && row.amount / 100 }}</div>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.actions')" align="center" :width="100">
            <template slot-scope="{ row }">
              <el-button size="mini" type="text" @click="openExpenses(row)"> {{ $t('table.edit') }} </el-button>
              <el-button size="mini" type="text" @click="deleteExpenses(row)">
                <span class="gl_color_error">{{ $t('table.delete') }}</span>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row class="gl_pt_20">
      <el-col align="center">
        <el-button :loading="buLoading" size="mini" type="primary" @click="application()">应用</el-button>
      </el-col>
    </el-row>
    <edit-expenses ref="editExpenses" @refreshPage="getExpensesList()" />
  </div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
import editExpenses from './editExpenses';
import { Api_GET_CompetitionChargeQO, Api_POST_CompetitionChargeVO } from '@/lib/form/events';
import {
  api_PUT_CompetitionCategoryChargeCompetitionChargeType, // 应用计费模式
  api_GET_CompetitionCategoryCharge, // 获取按项目计费列表
  api_POST_CompetitionCategoryCharge, // 创建按项目计费
  api_PUT_CompetitionCategoryChargeId, // 更新费用
  api_GET_CompetitionCategoryOtherCharge,
  api_DELETE_CompetitionCategoryOtherChargeId,
  api_POST_CompetitionCategoryOtherCharge,
  api_PUT_CompetitionCategoryOtherChargeId
} from '@/extend/api/game.js';
import { CopyData } from '@/lib';
export default {
  name: 'Expenses',
  components: {
    editExpenses
  },
  data() {
    return {
      projectLoading: false,
      showTableLoading: false,
      tableLoading: false,
      buLoading: false,
      api_GET_CompetitionChargeQO: new Api_GET_CompetitionChargeQO(),
      api_POST_CompetitionChargeVO: new Api_POST_CompetitionChargeVO(),
      showTableData: [],
      tableData: [],
      projectObj: {
        aType: [],
        bType: [],
        cType: [],
        team: []
      }
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict
    })
  },
  created() {
    this.showTableLoading = true;
    this.init();
    this.getProjectExpensesList();
    Promise.all([this.getDict(), this.getExpensesList()]).then(() => {
      this.handleLeftExpenses();
      this.showTableLoading = false;
    }, () => {
      this.showTableLoading = false;
    });
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    init() {
      this.gameId = this.$route.params.id;
      this.api_GET_CompetitionChargeQO = new Api_GET_CompetitionChargeQO();
      this.api_GET_CompetitionChargeQO.IncludeChargeType = true;
      this.api_GET_CompetitionChargeQO.competitionId = this.gameId;
    },
    // 获取费用列表
    getExpensesList() {
      return new Promise((resolve, reject) => {
        this.tableLoading = true;
        this.showTableLoading = true;
        api_GET_CompetitionCategoryOtherCharge(this.api_GET_CompetitionChargeQO).then(res => {
          this.tableLoading = false;
          this.showTableLoading = false;
          this.tableData = res.items || [];
          this.handleLeftExpenses();
          resolve(res);
        }, () => {
          this.tableLoading = false;
          this.showTableLoading = false;
          this.$message({ type: 'error', message: '获取费用列表失败！' });
          reject();
        });
      });
    },
    // 获取项目计费列表
    getProjectExpensesList() {
      var that = this;
      that.projectLoading = true;
      const form = {
        competitionId: this.gameId
      };
      api_GET_CompetitionCategoryCharge(form).then(res => {
        that.handleProjectData(res);
        that.projectLoading = false;
      }, (error) => {
        that.projectLoading = false;
        that.$message({ type: 'error', message: error.error.message });
      });
    },
    // 处理项目计费数据
    handleProjectData(data) {
      this.projectObj = {
        aType: [],
        bType: [],
        cType: [],
        team: []
      };
      for (let i = 0; i < data.length; i++) {
        const item = data[i];
        if (!item.charge) {
          item.charge = {
            entryAmount: 0,
            simultaneousEntryAmountA: 0,
            simultaneousEntryAmountB: 0,
            simultaneousEntryAmountC: 0
          };
        } else {
          item.charge.entryAmount = item.charge.entryAmount && item.charge.entryAmount / 100;
          item.charge.simultaneousEntryAmountA = item.charge.simultaneousEntryAmountA && item.charge.simultaneousEntryAmountA / 100;
          item.charge.simultaneousEntryAmountB = item.charge.simultaneousEntryAmountB && item.charge.simultaneousEntryAmountB / 100;
          item.charge.simultaneousEntryAmountC = item.charge.simultaneousEntryAmountC && item.charge.simultaneousEntryAmountC / 100;
        }
        if (item.categoryGroupTypeCode === 'C') {
          this.projectObj.cType.push(item);
        } else if (item.categoryGroupTypeCode === 'B') {
          this.projectObj.bType.push(item);
        } else if (item.categoryGroupTypeCode === 'A') {
          this.projectObj.aType.push(item);
        } else {
          this.projectObj.team.push(item);
        }
      }
      console.log(this.projectObj);
    },
    // 删除
    deleteExpenses(expensesInfo) {
      this.$confirm(`您确定要删除该费用吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableLoading = true;
        api_DELETE_CompetitionCategoryOtherChargeId(expensesInfo.id).then(() => {
          this.getExpensesList();
          this.$message({ type: 'success', message: '删除成功！' });
        }, () => {
          this.tableLoading = false;
          this.$message({ type: 'error', message: '删除失败！' });
        });
      }).catch(() => {});
    },
    // 处理左侧显示的费用类型
    handleLeftExpenses() {
      if (!this.dict.competitionChargeType) return;
      const competitionChargeType = this.dict.competitionChargeType;
      const expeneseType = [];
      // 初始化字典
      for (let i = 0; i < competitionChargeType.length; i++) {
        const item = competitionChargeType[i];
        // 非自定义
        if (item.code === 'Custom' || item.code === 'Entry' || item.code === 'SimultaneousEntry') continue;
        const api_POST_CompetitionChargeVO = new Api_POST_CompetitionChargeVO();
        api_POST_CompetitionChargeVO.chargeTypeCode = item.code;
        api_POST_CompetitionChargeVO.name = item.value;
        expeneseType.push(api_POST_CompetitionChargeVO);
      }
      // 赋值回显
      const addExpeneseType = [];
      for (let i = 0; i < this.tableData.length; i++) {
        const item = this.tableData[i];
        for (let j = 0; j < expeneseType.length; j++) {
          const jtem = expeneseType[j];
          if (item.name === jtem.name) {
            CopyData(item, jtem);
            jtem.amount = jtem.amount && jtem.amount / 100;
            jtem.id = item.id;
            break;
          }
          if (j === expeneseType.length - 1) {
            const api_POST_CompetitionChargeVO = new Api_POST_CompetitionChargeVO();
            CopyData(item, api_POST_CompetitionChargeVO);
            api_POST_CompetitionChargeVO.amount = api_POST_CompetitionChargeVO.amount && api_POST_CompetitionChargeVO.amount / 100;
            api_POST_CompetitionChargeVO.id = item.id;
            addExpeneseType.push(api_POST_CompetitionChargeVO);
          }
        }
      }
      this.showTableData = expeneseType.concat(addExpeneseType);
    },
    openExpenses(expensesInfo) {
      this.$refs.editExpenses.open(expensesInfo, 'project');
    },
    // 提交费用（项目）
    submitProjectExpenses(expensesInfo) {
      console.log(expensesInfo);
      const form = {
        competitionId: this.gameId,
        categoryId: expensesInfo.categoryId,
        entryAmount: Number(expensesInfo.charge.entryAmount) * 100,
        simultaneousEntryAmountA: Number(expensesInfo.charge.simultaneousEntryAmountA) * 100,
        simultaneousEntryAmountB: Number(expensesInfo.charge.simultaneousEntryAmountB) * 100,
        simultaneousEntryAmountC: Number(expensesInfo.charge.simultaneousEntryAmountC) * 100
      };
      if (form.entryAmount || form.simultaneousEntryAmountA || form.simultaneousEntryAmountB || form.simultaneousEntryAmountC) {
        if (expensesInfo.charge.id) {
          this.editProjectExpenses(expensesInfo.charge.id, form).then(res => {
            this.$message({ type: 'success', message: '提交成功！' });
            this.getProjectExpensesList();
          }, error => {
            this.$message({ type: 'error', message: '编辑赛事费用失败！' + error.error.message });
          });
        } else {
          this.addProjectExpenses(form).then(res => {
            this.$message({ type: 'success', message: '提交成功！' });
            this.getProjectExpensesList();
          }, error => {
            this.$message({ type: 'error', message: '新增赛事费用失败！' + error.error.message });
          });
        }
      } else {
        this.$message({ type: 'warning', message: '请输入金额！' });
      }
    },
    // 新增赛事费用（项目）
    addProjectExpenses(form) {
      return new Promise((resolve, reject) => {
        this.loading = true;
        api_POST_CompetitionCategoryCharge(form).then(res => {
          resolve(res);
        }, error => {
          reject(error);
        });
      });
    },
    // 编辑赛事费用（项目）
    editProjectExpenses(id, form) {
      return new Promise((resolve, reject) => {
        this.loading = true;
        api_PUT_CompetitionCategoryChargeId(id, form).then(res => {
          resolve(res);
        }, error => {
          reject(error);
        });
      });
    },
    // 提交费用
    submitExpenses(expensesInfo) {
      console.log(expensesInfo);
      if (!expensesInfo.amount) {
        this.$message({ type: 'warning', message: '请输入金额！' });
        return;
      }
      expensesInfo.competitionId = this.gameId;
      const _api_POST_CompetitionChargeVO = JSON.parse(JSON.stringify(expensesInfo));
      _api_POST_CompetitionChargeVO.amount = Number(_api_POST_CompetitionChargeVO.amount) * 100;
      if (_api_POST_CompetitionChargeVO.id) {
        this.editExpenses(_api_POST_CompetitionChargeVO);
      } else {
        this.addExpenses(_api_POST_CompetitionChargeVO);
      }
    },
    // 新增赛事费用
    addExpenses(api_POST_CompetitionChargeVO) {
      return new Promise((resolve, reject) => {
        this.loading = true;
        api_POST_CompetitionCategoryOtherCharge(api_POST_CompetitionChargeVO).then(res => {
          resolve(res);
          this.getExpensesList();
        }, error => {
          reject(error);
          this.$message({ type: 'error', message: '新增赛事费用失败！' + error.error.message });
        });
      });
    },
    // 编辑赛事费用
    editExpenses(api_POST_CompetitionChargeVO) {
      return new Promise((resolve, reject) => {
        this.loading = true;
        api_PUT_CompetitionCategoryOtherChargeId(api_POST_CompetitionChargeVO.id, api_POST_CompetitionChargeVO).then(res => {
          this.getExpensesList();
          resolve(res);
        }, error => {
          reject(error);
          this.$message({ type: 'error', message: '编辑赛事费用失败！' + error.error.message });
        });
      });
    },
    // 应用计费模式
    application() {
      var that = this;
      that.buLoading = true;
      const form = {
        competitionId: this.gameId,
        chargeTypeCode: 'Category'
      };
      api_PUT_CompetitionCategoryChargeCompetitionChargeType(form).then(res => {
        that.$message({ type: 'success', message: '应用成功' });
        that.buLoading = false;
        that.$emit('refreshSetting');
      }, (error) => {
        that.buLoading = false;
        that.$message({ type: 'error', message: error.error.message });
      });
    }
  }
};
</script>
<style lang="scss">
.project_expenses {
  .expenses_table .form_name {
    display: inline-block;
    width: 180px;
  }
  .expenses_table .bottom_form_name {
    display: inline-block;
    width: 80px;
  }
  .el-table, .el-table__body-wrapper {
    min-height: auto;
  }
}
</style>
